<?php

	class admin {

	
		var $managerid = "";
		var $managerusername = "";
		var $managerrealname = "";		


		function admin() {
			global $db, $config, $uri;
		
			if(!empty($_SESSION["managerid"])) { 

				$managerid = $db->qstr($_SESSION["managerid"]);
				
				$_SESSION["managerid"]=null;
				$_SESSION["managerusername"]=null;
				$_SESSION["managerrealname"]=null;
				$_SESSION["managerrights"]=null;
				$rss = $db->getrow("select * from {$config->db_prefix}managers where id=$managerid and locked!=1");
				if($rss) {
					if($rss["rights"]=="administrator") $_SESSION["managerrights"] = $rss["rights"];
					else {
						$rsr = split(";", $rss["rights"]);
						foreach($rsr as $k => $v) $_SESSION["managerrights"][$v] = 1;
					}
					$_SESSION["managerid"] = $rss["id"];
					$_SESSION["managerusername"] = $rss["username"];
					$_SESSION["managerrealname"] = $rss["realname"];
				}
				else
					$uri = "admin/index";
					
			}
		}

		function login() {
			global $uri;

			$uri = "admin/index";
		}


		function _login($username="", $password="") {
			global $db, $smarty, $config;
			
			if(empty($username)) $errors["empty_username"] = true;
			if(empty($password)) $errors["empty_password"] = true;
			
			if(empty($errors)) {
				
				$sqlstr = "select * from {$config->db_prefix}managers where username=".$db->qstr($username)." or email=".$db->qstr($username);
				$rss = $db->getrow($sqlstr);
				if(!$rss) $errors["empty_member"] = true;
				else if($rss["password"]!=md5($password)) $errors["wrong_password"] = true;
				else if($rss["locked"]) $errors["member_locked"] = true;					

				if(empty($errors)) {	
					$logdate = time();
					$ipaddress = $db->qstr($_SERVER['REMOTE_ADDR']);
					$db->execute("update {$config->db_prefix}managers set logdate=$logdate, ipaddress=$ipaddress, logcount=logcount+1 where id=".$rss["id"]);
					$_SESSION["managerid"] = $rss["id"];
					$_SESSION["managerusername"] = $rss["username"];
					$_SESSION["managerrealname"] = $rss["realname"];
					if($rss["rights"]=="administrator") $_SESSION["managerrights"] = $rss["rights"];
					else {
						$rsr = split(";", $rss["rights"]);
						foreach($rsr as $k => $v) $_SESSION["managerrights"][$v] = 1;
					}
					
					setcookie("managerusername", $rss["username"], time()+3600*24*30, "/");			
				}
			}

			if(!empty($errors)) $smarty->assign("errors", $errors);
			else
 				return true;
		}


		function _logout() {
				$_SESSION["managerid"]=null;
				$_SESSION["managerusername"]=null;
				$_SESSION["managerrealname"]=null;
				$_SESSION["managerrights"]=null;
			session_unset();
		}
		
		function rights($right) {
			global $uri;
		
			if($_SESSION["managerrights"]!="administrator") {
				$rights = explode("|", $right);
				$yesshow = 0;
				foreach($rights as $k => $v) if($_SESSION["managerrights"][$v]==1) $yesshow = 1;
				if(!$yesshow) $uri = "admin/index";
				return false;
			}
			
			return true;
		}

}
?>